package com.xbjtech.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xbjtech.model.User;
import com.xbjtech.util.AppConfig;

public class TokenFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String uri = request.getRequestURI();
		uri = uri.replaceFirst(request.getServletContext().getContextPath(), "");
		User user = (User) request.getSession().getAttribute(AppConfig.LOGIN_USER_SESSION);
		boolean flag = false;
		if (uri.equals("/login")) {
			flag = true;
		} else if (uri.startsWith("/assets/")) {
			flag = true;
		} else if (user != null) {
			flag = true;
		}
		if (flag) {
			chain.doFilter(req, resp);
		} else {
			((HttpServletResponse) resp)
			.sendRedirect(
					request.getServletContext().getContextPath() + "/login");
		}
	}

	@Override
	public void destroy() {
	}
}
